//
//  USAddOurListDetailVC.m
//  us
//
//  Created by karry on 2025/5/26.
//

#import "USAddOurListDetailVC.h"
#import "USOurListDoneView.h"
#import "USMediaUploadManager.h"
@interface USAddOurListDetailVC () <PHPickerViewControllerDelegate>
@property (weak, nonatomic) IBOutlet UIView *topView;
@property (weak, nonatomic) IBOutlet UIButton *selectBtn;
@property (weak, nonatomic) IBOutlet UILabel *titleLab;
@property (weak, nonatomic) IBOutlet UILabel *timeLab;
@property (weak, nonatomic) IBOutlet UIView *bgView;
@property (weak, nonatomic) IBOutlet UIImageView *imageView;

@property (nonatomic,strong) USOurListDoneView *doneView;


@end

@implementation USAddOurListDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.navigationItem.title = @"小事详情";
    
    [self setupView];
    [self loadData];
}
 
- (void)setupView {
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage systemImageNamed:@"ellipsis"] style:UIBarButtonItemStylePlain target:self action:@selector(moreAction:event:)];

    self.bgView.layer.cornerRadius = 14;
    self.bgView.backgroundColor = UIColor.mi_1_color;
    [self.bgView jk_shadowWithColor:UIColor.lightGrayColor offset:CGSizeMake(3, 3) opacity:0.2 radius:3];

    self.imageView.layer.cornerRadius = 10;
    self.imageView.layer.masksToBounds = YES;
    self.imageView.userInteractionEnabled = YES;
    UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(chooseImg)];
    [self.imageView addGestureRecognizer:recognizer];
    
    [self.view addSubview:self.doneView];
    CGFloat stickerViewH = 460 + self.view.window.safeAreaInsets.bottom;
    [self.doneView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_safeAreaLayoutGuideLeft);
        make.right.mas_equalTo(self.view.mas_safeAreaLayoutGuideRight);
        make.bottom.mas_offset(stickerViewH);
        make.height.mas_equalTo(stickerViewH);
    }];
    
  
}

- (void)loadData {
    [super loadData];
    
    
    self.titleLab.text = self.itemModel.taskTitle;
    self.timeLab.text = [NSDateFormatter localizedStringFromDate:[NSDate dateWithTimeIntervalSince1970:self.itemModel.completionTime] dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterNoStyle];
    if (self.itemModel.taskPicUrl.length > 0) {
        [self.imageView sd_setImageWithURL:[NSURL URLWithString:self.itemModel.taskPicUrl]];

    }else{
        self.imageView.image = [UIImage imageNamed:@"list_detail_empty"];
        
    }
    
    [self.selectBtn setSelected:self.itemModel.completionStatus];

}

- (USOurListDoneView *)doneView {
    if (_doneView == nil) {
        _doneView = [USOurListDoneView jk_loadInstanceFromNib];
        _doneView.hidden = YES;
        @weakify(self)
        _doneView.listDoneBlock = ^{
         @strongify(self)
            [self requestEditList];
        };
    }
    return _doneView;
}

 
#pragma mark - action
- (void)chooseImg {
    [USFeedbackTool impactSoft];

    PHPickerConfiguration *config = [[PHPickerConfiguration alloc] init];
    config.selectionLimit = 1; // 只选一张图
    config.filter = [PHPickerFilter imagesFilter]; // 只显示图片

    PHPickerViewController *picker = [[PHPickerViewController alloc] initWithConfiguration:config];
    picker.delegate = self;
    [UIViewController.topViewController presentViewController:picker animated:YES completion:nil];
}

// 代理回调
- (void)picker:(PHPickerViewController *)picker didFinishPicking:(NSArray<PHPickerResult *> *)results {
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    PHPickerResult *result = results.firstObject;
    if (result) {
        [result.itemProvider loadObjectOfClass:[UIImage class] completionHandler:^(UIImage *image, NSError *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (image) {

//                    self.imageView.image = image;
                    
                    [self uploadImage:image];
                }
            });
        }];
    }
}
- (void)uploadImage:(UIImage *)image {
    [EMHudManager show:@"上传中..."];

    [USMediaUploadManager uploadImageToCOS:image progress:^(CGFloat progress) {
        [EMHudManager showProgress: progress];
        [EMHudManager show:[NSString stringWithFormat:@"上传中 %i%%", (int)progress * 100]];
    } success:^(NSString * _Nonnull cosUrl) {
        
        self.itemModel.taskPicUrl = cosUrl;
        NSLog(@"图片上传成功");
        self.doneView.itemModel = self.itemModel;
        [self requestEditList];
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

- (void)moreAction:(UIBarButtonItem *)sender event:(UIEvent *)event{
    
    [USFeedbackTool impactMedium];
    
    UIView *view = [event.allTouches anyObject].view;
    
    DTItem *takePhoto = [DTItem itemWithTitle:@"编辑" image:[UIImage imageNamed:@"icon-edit-22"] tag:0 identifier:nil handle:^(DTItem *item) {
        [self editAction];
    }];
    
    DTItem *choosePhoto = [DTItem itemWithTitle:@"删除" image:[UIImage imageNamed:@"icon-trash-22"] tag:0 identifier:nil handle:^(DTItem *item) {
        [self deleteAction];
        
    }];
    
    
    DTTargetView *targetView = [[DTTargetView alloc]initWithTargetView:view item:@[takePhoto,choosePhoto]];
    
    [targetView show];
    
}
- (void)editAction {
    self.doneView.itemModel = self.itemModel;
    [self.doneView showLitPickerWithAllowTapDismiss:YES];
    
}

- (void)deleteAction {
    MOAlertBaseView *alert = [[MOAlertBaseView alloc]initWithTitle:@"确定删除此小事吗" detailTitle:@"此操作不可撤销哦，请谨慎操作" contentView:nil leftButtonImageName:nil rightButtonImageName:nil autoDissmiss:YES tapDissmiss:YES];
    alert.titleLabel.textColor = UIColor.us_redColor;
    @weakify(self)
    alert.didClickIndexBlock = ^(NSInteger index) {
        @strongify(self)
        if (index == 1) {
            [self deleteList];
        }
    };
    
    [alert show];

    
}

- (void)deleteList {
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"challengeTaskId"] = self.itemModel.challengeTaskId;
    
    [[EMNetWork shareManager] em_post:API_DailyChallengeTaskDelete
                               params:params
                                  hud:nil
                            showError:YES
                              success:^(EMApiModel *api) {
        
        
        if (!api.success) {
            return;
        }
        [USFeedbackTool notifySuccess];
        [self.navigationController popViewControllerAnimated:YES];
        
    } fail:^{
        
        
    }];
}

 
 
- (void)requestEditList {
    [USFeedbackTool impactSoft];
 
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    params[@"completionStatus"] = @(self.itemModel.completionStatus);

    
    params[@"taskTitle"] = self.itemModel.taskTitle;
    params[@"completionTime"] = @(self.itemModel.completionTime);
    params[@"taskPicUrl"] = self.itemModel.taskPicUrl;

    params[@"sweetChallengeId"] = self.itemModel.sweetChallengeId?:@"";
    params[@"challengeTaskId"] = self.itemModel.challengeTaskId;

    [[EMNetWork shareManager] em_post:API_DailyChallengeTaskEdit
                               params:params
                                  hud:nil
                           showError:YES
                              success:^(EMApiModel *api) {
 
        if (!api.success) {
            return;
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self loadData];
        });
    } fail:^{
         
    }];
    
    
}

@end
